// Copyright (c) Microsoft Corporation. All rights reserved.

namespace SPPivotViewer.HttpHandler.Internal
{
    using System;
    using System.Drawing;
    using System.Drawing.Drawing2D;
    using System.Collections.Generic;
using System.Net;
    using SPPivotViewer.Utility;
    using Microsoft.SharePoint;
    using System.IO;


    /// <summary>
    /// Create an image by drawing it, using the name and description. 
    /// </summary>
    internal class DynamicImage : ImageBase
    {
        // Constructors, Finalizer and Dispose
        //======================================================================

        public DynamicImage(string name, Dictionary<string,string> MetaData)
        {
            m_title = name;
            m_metadata = MetaData;
        }


        // Protected Methods
        //======================================================================

        protected override Image[] MakeImage()
        {
            return DrawBitmap(m_title, m_metadata);
        }


        // Private Methods
        //======================================================================

        private Image[] DrawBitmap(string title, Dictionary<string,string> metadata)
        {
            using (WebClient web = new WebClient())
            {
                web.UseDefaultCredentials = true;
                List<Image> imgReturn = new List<Image>();

                string strImgSub = PV4SPSettings.GetValue(SPContext.Current.Web, PV4SPSettings.cstImgSub);
                if (strImgSub != string.Empty)
                {
                    using (Stream webStream = web.OpenRead(strImgSub))
                    {
                        using (Image img = Image.FromStream(webStream))
                        {
                            FillLayers(img, m_title, m_metadata, ref imgReturn);
                        }
                    }

                }
                else
                {
                    using (Image img = Image.FromStream(this.GetType().Assembly.GetManifestResourceStream("SPPivotViewer.Resources.pv4sp256.png")))
                    {
                        FillLayers(img, m_title, m_metadata, ref imgReturn);
                    }
                }
                return imgReturn.ToArray();
            }

            
        }

        

        string m_title;
        Dictionary<string,string> m_metadata;
    }
}